package com.yy.common.intercept;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yy.common.core.AjaxResult;
import com.yy.common.utils.JwtHelper;
import com.yy.pojo.User;
import com.yy.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * ClassName: SystemManagerIntercepter
 * Package: com.yy.interceptor
 * Description:
 *
 * @Author yy
 * @Create 2023-12-29 4:45
 * @Version 1.0
 */
@Component
public class SystemManagerIntercepter implements HandlerInterceptor {
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token) || jwtHelper.isExpiration(token)) {
            AjaxResult ajaxResult = AjaxResult.error("用户尚未登录！");
            response.setContentType("application/json; charset=utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(ajaxResult);
            response.getWriter().print(json);
            return false;
        }
        Long userId = jwtHelper.getUserId(token);
        User user = userService.getById(userId);
        String userType = user.getUserType();
        return "00".equals(userType);
    }

}
